from rest_framework import generics, permissions
from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response
from django.utils import timezone
from django.db.models import Count, Sum, Avg
from django.db.models.functions import TruncDate, TruncMonth
from datetime import timedelta, datetime
from .models import (
    PageView, SearchQuery, UserActivity,
    SalesReport, PopularBook, TrafficSource,
    ConversionFunnel, ABNTest
)
from .serializers import (
    DashboardStatsSerializer, SalesTrendSerializer,
    UserActivityReportSerializer, SearchAnalyticsSerializer,
    TopSellingBookSerializer, CategoryPerformanceSerializer
)
from orders.models import Order
from books.models import Book, Category
from users.models import User


@api_view(['GET'])
@permission_classes([permissions.IsAdminUser])
def dashboard_stats(request):
    today = timezone.now().date()
    last_7_days = today - timedelta(days=7)
    
    # 用户统计
    total_users = User.objects.count()
    new_users_today = User.objects.filter(
        date_joined__date=today
    ).count()
    
    # 订单统计
    total_orders = Order.objects.count()
    today_orders = Order.objects.filter(
        created_at__date=today
    ).count()
    
    # 收入统计
    total_revenue = Order.objects.filter(
        status__in=['completed', 'delivered']
    ).aggregate(
        total=Sum('final_amount')
    )['total'] or 0
    
    today_revenue = Order.objects.filter(
        created_at__date=today,
        status__in=['completed', 'delivered']
    ).aggregate(
        total=Sum('final_amount')
    )['total'] or 0
    
    # 待处理订单
    pending_orders = Order.objects.filter(
        status='pending'
    ).count()
    
    # 图书统计
    total_books = Book.objects.count()
    
    # 库存预警
    from inventory.models import StockAlert
    low_stock_books = StockAlert.objects.filter(
        is_resolved=False
    ).count()
    
    stats = DashboardStatsSerializer({
        'total_users': total_users,
        'total_orders': total_orders,
        'total_revenue': total_revenue,
        'total_books': total_books,
        'today_orders': today_orders,
        'today_revenue': today_revenue,
        'pending_orders': pending_orders,
        'low_stock_books': low_stock_books
    }).data
    
    return Response(stats)


@api_view(['GET'])
@permission_classes([permissions.IsAdminUser])
def sales_trend(request):
    days = int(request.GET.get('days', 30))
    end_date = timezone.now().date()
    start_date = end_date - timedelta(days=days)
    
    orders = Order.objects.filter(
        created_at__date__gte=start_date,
        created_at__date__lte=end_date,
        status__in=['completed', 'delivered']
    ).annotate(
        date=TruncDate('created_at')
    ).values('date').annotate(
        orders=Count('id'),
        revenue=Sum('final_amount')
    ).order_by('date')
    
    serializer = SalesTrendSerializer(orders, many=True)
    return Response(serializer.data)


@api_view(['GET'])
@permission_classes([permissions.IsAdminUser])
def user_activity_report(request):
    days = int(request.GET.get('days', 30))
    end_date = timezone.now().date()
    start_date = end_date - timedelta(days=days)
    
    # 每日用户活动
    daily_activity = User.objects.filter(
        date_joined__date__gte=start_date
    ).annotate(
        date=TruncDate('date_joined')
    ).values('date').annotate(
        new_users=Count('id')
    ).order_by('date')
    
    # 活跃用户
    active_users = UserActivity.objects.filter(
        created_at__date__gte=start_date
    ).annotate(
        date=TruncDate('created_at')
    ).values('date').annotate(
        active_users=Count('user', distinct=True)
    ).order_by('date')
    
    # 页面浏览量
    page_views = PageView.objects.filter(
        created_at__date__gte=start_date
    ).annotate(
        date=TruncDate('created_at')
    ).values('date').annotate(
        page_views=Count('id')
    ).order_by('date')
    
    # 合并数据
    report_data = []
    for date in [start_date + timedelta(days=x) for x in range(days + 1)]:
        date_str = date.isoformat()
        
        new_users = next(
            (item['new_users'] for item in daily_activity if str(item['date']) == date_str),
            0
        )
        
        active_users_count = next(
            (item['active_users'] for item in active_users if str(item['date']) == date_str),
            0
        )
        
        page_views_count = next(
            (item['page_views'] for item in page_views if str(item['date']) == date_str),
            0
        )
        
        report_data.append({
            'date': date_str,
            'new_users': new_users,
            'active_users': active_users_count,
            'page_views': page_views_count,
            'unique_visitors': active_users_count  # 简化处理
        })
    
    serializer = UserActivityReportSerializer(report_data, many=True)
    return Response(serializer.data)


@api_view(['GET'])
@permission_classes([permissions.IsAdminUser])
def search_analytics(request):
    days = int(request.GET.get('days', 30))
    end_date = timezone.now().date()
    start_date = end_date - timedelta(days=days)
    
    search_queries = SearchQuery.objects.filter(
        created_at__date__gte=start_date
    ).values('query').annotate(
        count=Count('id'),
        conversion_rate=Avg('has_results')
    ).order_by('-count')[:20]
    
    serializer = SearchAnalyticsSerializer(search_queries, many=True)
    return Response(serializer.data)


@api_view(['GET'])
@permission_classes([permissions.IsAdminUser])
def top_selling_books(request):
    days = int(request.GET.get('days', 30))
    end_date = timezone.now().date()
    start_date = end_date - timedelta(days=days)
    
    top_books = Order.objects.filter(
        created_at__date__gte=start_date,
        status__in=['completed', 'delivered']
    ).values(
        'items__book__id',
        'items__book__title'
    ).annotate(
        total_sold=Sum('items__quantity'),
        total_revenue=Sum('items__subtotal')
    ).order_by('-total_sold')[:10]
    
    serializer = TopSellingBookSerializer(top_books, many=True)
    return Response(serializer.data)


@api_view(['GET'])
@permission_classes([permissions.IsAdminUser])
def category_performance(request):
    days = int(request.GET.get('days', 30))
    end_date = timezone.now().date()
    start_date = end_date - timedelta(days=days)
    
    category_performance = Order.objects.filter(
        created_at__date__gte=start_date,
        status__in=['completed', 'delivered']
    ).values(
        'items__book__categories__name'
    ).annotate(
        total_sales=Sum('items__quantity'),
        total_revenue=Sum('items__subtotal'),
        average_rating=Avg('items__book__reviews__rating')
    ).order_by('-total_revenue')
    
    serializer = CategoryPerformanceSerializer(category_performance, many=True)
    return Response(serializer.data)


@api_view(['GET'])
@permission_classes([permissions.IsAdminUser])
def traffic_overview(request):
    days = int(request.GET.get('days', 7))
    end_date = timezone.now().date()
    start_date = end_date - timedelta(days=days)
    
    # 页面浏览量
    total_page_views = PageView.objects.filter(
        created_at__date__gte=start_date
    ).count()
    
    # 独立访客
    unique_visitors = PageView.objects.filter(
        created_at__date__gte=start_date
    ).values('session_id').distinct().count()
    
    # 搜索查询
    total_searches = SearchQuery.objects.filter(
        created_at__date__gte=start_date
    ).count()
    
    # 用户活动
    total_activities = UserActivity.objects.filter(
        created_at__date__gte=start_date
    ).count()
    
    return Response({
        'total_page_views': total_page_views,
        'unique_visitors': unique_visitors,
        'total_searches': total_searches,
        'total_activities': total_activities
    })


@api_view(['GET'])
@permission_classes([permissions.IsAdminUser])
def conversion_funnel(request):
    days = int(request.GET.get('days', 30))
    end_date = timezone.now().date()
    start_date = end_date - timedelta(days=days)
    
    # 访客数
    visitors = PageView.objects.filter(
        created_at__date__gte=start_date
    ).values('session_id').distinct().count()
    
    # 产品浏览数
    product_views = PageView.objects.filter(
        created_at__date__gte=start_date,
        path__contains='/books/'
    ).values('session_id').distinct().count()
    
    # 加入购物车
    cart_additions = UserActivity.objects.filter(
        created_at__date__gte=start_date,
        activity_type='add_to_cart'
    ).values('user').distinct().count()
    
    # 下单数
    orders = Order.objects.filter(
        created_at__date__gte=start_date
    ).count()
    
    # 完成订单数
    completed_orders = Order.objects.filter(
        created_at__date__gte=start_date,
        status__in=['completed', 'delivered']
    ).count()
    
    funnel = [
        {
            'step_name': '访客',
            'visitors': visitors,
            'conversions': visitors,
            'conversion_rate': 100.0,
            'drop_off_rate': 0.0
        },
        {
            'step_name': '产品浏览',
            'visitors': visitors,
            'conversions': product_views,
            'conversion_rate': (product_views / visitors * 100) if visitors > 0 else 0,
            'drop_off_rate': ((visitors - product_views) / visitors * 100) if visitors > 0 else 0
        },
        {
            'step_name': '加入购物车',
            'visitors': product_views,
            'conversions': cart_additions,
            'conversion_rate': (cart_additions / product_views * 100) if product_views > 0 else 0,
            'drop_off_rate': ((product_views - cart_additions) / product_views * 100) if product_views > 0 else 0
        },
        {
            'step_name': '下单',
            'visitors': cart_additions,
            'conversions': orders,
            'conversion_rate': (orders / cart_additions * 100) if cart_additions > 0 else 0,
            'drop_off_rate': ((cart_additions - orders) / cart_additions * 100) if cart_additions > 0 else 0
        },
        {
            'step_name': '完成订单',
            'visitors': orders,
            'conversions': completed_orders,
            'conversion_rate': (completed_orders / orders * 100) if orders > 0 else 0,
            'drop_off_rate': ((orders - completed_orders) / orders * 100) if orders > 0 else 0
        }
    ]
    
    return Response(funnel)
